package org.opens.javaskill.design.apply;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * 说明:
 * <pre>
 *     1. 这种设计模式的核心思想就是反向逻辑-如果检测到程序不满足条件则立即终止.
 * </pre>
 * @Date 2020/9/17 20:49
 * @Created by 99126
 */
public class BalkingPattern {

    public static void main(String[] args) {
        BalkingData balkingData = new BalkingData("e://a.txt", "str");
        balkingData.change("aaaaaaa");
        balkingData.save();
        balkingData.change("ddddddd");
        balkingData.save();
        balkingData.change("eeeeeee");
        balkingData.save();
    }

}

class BalkingData {

    private final String fileName;

    private String content;

    private boolean changed;

    public BalkingData(String fileName, String content) {
        this.fileName = fileName;
        this.content = content;
        this.changed = true;
    }

    public synchronized void change(String newContent) {
        this.content = newContent;
        this.changed = true;
    }

    public synchronized void save() {
        // 无变化则直接返回, 这里就是balking思想的核心-反向逻辑
        if (!changed) {
            return;
        }
        doSave();
        this.changed = false;
    }

    private void doSave() {
        System.out.println(Thread.currentThread().getName() + " doSave");
        // 这是try...with...resource语法, 会自动关闭括号中的资源
        try (Writer writer = new FileWriter(fileName, true)) {
            writer.write(this.content);
            writer.write("\n");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}